package com.easy.controller;

import com.easy.bean.Staff;
import com.easy.mapper.StaffDao;
import com.easy.service.LoginService;
import com.easy.util.EmailUtil;
import com.easy.util.Result;
import com.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("forget")
@CrossOrigin
public class ForgetPasswordController {

    @Autowired
    private StaffDao staffDao;

    // 存储验证码的临时存储，实际项目中应该使用Redis等缓存
    private static final Map<String, String> verificationCodes = new ConcurrentHashMap<>();
    private static final Map<String, Long> codeExpiryTimes = new ConcurrentHashMap<>();

    /**
     * 发送验证码到邮箱
     * @param email 用户邮箱
     * @return
     */
    @PostMapping("/send-code")
    @ResponseBody
    public Result sendVerificationCode(@RequestParam("email") String email) {
        // 查找邮箱对应的用户
        Staff staff = staffDao.getByEmail(email);
        if (staff == null) {
            return Result.fail(500, "用户不存在");
        }

        try {
            // 生成6位验证码
            String code = String.format("%06d", new Random().nextInt(999999));

            // 发送邮件
            EmailUtil.sendEmail(email, code);

            // 存储验证码和过期时间(5分钟)
            verificationCodes.put(email, code);
            codeExpiryTimes.put(email, System.currentTimeMillis() + 5 * 60 * 1000);

            return Result.success("验证码已发送至您的邮箱");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "发送验证码失败");
        }
    }

    /**
     * 重置密码
     * @param email 用户邮箱
     * @param code 验证码
     * @return
     */
    @PostMapping("/reset-password")
    @ResponseBody
    public Result resetPassword(@RequestParam("email") String email,
                                @RequestParam("code") String code) {
        try {
            // 验证验证码
            if (!verifyCode(email, code)) {
                return Result.fail(500, "验证码错误或已过期");
            }

            // 查找用户
            Staff staff = staffDao.getByEmail(email);
            if (staff == null) {
                return Result.fail(500, "用户不存在");
            }

            // 生成新密码
            String newPassword = generateRandomPassword(8);

            // 更新密码
            // 使用现有的密码加密工具
            staff.setPassword(com.easy.util.passwordUtil.getEncryption(newPassword));
            staffDao.edit(staff);

            // 发送新密码到用户邮箱
            try {
                EmailUtil.sendNewPassword(email, newPassword);
            } catch (Exception e) {
                e.printStackTrace();
                // 即使邮件发送失败，密码重置本身是成功的
                return Result.success("密码重置成功，但发送新密码到邮箱失败，请联系管理员");
            }

            // 清除验证码
            verificationCodes.remove(email);
            codeExpiryTimes.remove(email);

            return Result.success("密码重置成功，新密码已发送至您的邮箱");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "重置密码失败");
        }
    }

    /**
     * 验证验证码
     * @param email 邮箱
     * @param code 验证码
     * @return
     */
    private boolean verifyCode(String email, String code) {
        String storedCode = verificationCodes.get(email);
        Long expiryTime = codeExpiryTimes.get(email);

        if (storedCode == null || expiryTime == null) {
            return false;
        }

        if (System.currentTimeMillis() > expiryTime) {
            // 验证码已过期
            verificationCodes.remove(email);
            codeExpiryTimes.remove(email);
            return false;
        }

        return storedCode.equals(code);
    }

    /**
     * 生成随机密码
     * @param length 密码长度
     * @return 随机密码
     */
    private String generateRandomPassword(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%";
        Random random = new Random();
        StringBuilder password = new StringBuilder();

        for (int i = 0; i < length; i++) {
            password.append(chars.charAt(random.nextInt(chars.length())));
        }

        return password.toString();
    }
}
